<template>
  <div class="page-container">
    <!--工具栏-->
    <div class="toolbar" style="float:left;padding-top:10px;padding-left:15px;">
      <el-form :inline="true" :size="size">
        <el-form-item>
          <perm-button icon="fa fa-search" label="搜索" perms="info:adpic:list" type="primary" @click="findData()"/>
        </el-form-item>
        <el-form-item>
          <perm-button icon="fa fa-plus" label="新增" perms="info:adpic:add" type="success" @click="handleAdd"/>
        </el-form-item>
      </el-form>
    </div>
    <!--表格树内容栏-->
    <el-table :data="datas" stripe size="mini" style="width: 100%;"
              v-loading="loading" element-loading-text="拼命加载中" row-key="adpicId">
      <el-table-column prop="adId" header-align="center" align="center" width="100" label="ID">
      </el-table-column>
      <el-table-column  prop="adType" header-align="center" align="center" width="150" label="广告类型">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.adType === 'Banner图'" size="small">Banner图</el-tag>
          <el-tag v-else-if="scope.row.adType === '轮播图'" size="small" type="success">轮播图</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="originName" header-align="center" align="center" width="250" label="原图片名">
      </el-table-column>
      <el-table-column prop="picUrl" header-align="center" align="center" label="广告图片">
        <template slot-scope="scope">
          <img :src="scope.row.picUrl" width="400" height="100"/>
        </template>
      </el-table-column>
      <el-table-column
        prop="url" header-align="center" align="center" width="300" label="广告地址">
      </el-table-column>
      <el-table-column
        prop="status" header-align="center" align="center" width="150"  label="状态">
      </el-table-column>
      <el-table-column
        fixed="right" header-align="center" align="center" width="185" label="操作">
        <template slot-scope="scope">
          <perm-button icon="fa fa-edit" label="编辑" perms="info:adpic:update" @click="handleEdit(scope.row)"/>
          <perm-button icon="fa fa-trash" label="删除" perms="info:adpic:delete" type="danger" @click="handleDelete(scope.row)"/>
        </template>
      </el-table-column>
    </el-table>
    <!-- 新增修改界面 -->
    <el-dialog :title="!dataForm.adId ? '新增' : '修改'" width="30%" :visible.sync="dialogVisible" :close-on-click-modal="false">
      <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="submitForm()"
               label-width="120px" :size="size" style="text-align:left;">
        <el-form-item label="广告类型" prop="adType">
          <el-radio-group v-model="dataForm.adType">
            <el-radio-button v-for="(type, index) in adTypeList" :label="type" :key="index">{{ type }}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="图片名称" prop="originName">
          <el-input v-model="dataForm.originName" placeholder="上传图片原始名称"></el-input>
        </el-form-item>
        <el-form-item :label="dataForm.adType + '上传'" prop="adType">
          <el-upload
            class="upload"
            accept="image/jpeg,image/gif,image/png"
            :with-credentials="upload.credentials"
            :action="upload.url"
            :before-upload="handleBeforeUpload"
            :on-remove="handleRemove"
            :on-error="handleError"
            :on-success="handleSuccess"
            :limit="1"
            :on-exceed="handleExceed"
            :file-list="upload.files"
            list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png/gif文件，且不超过1MB</div>
          </el-upload>
          <span style="color:red;" v-text="upload.message"></span>
        </el-form-item>
        <el-form-item label="广告地址" prop="url">
          <el-input v-model="dataForm.url" placeholder="广告地址http://"></el-input>
        </el-form-item>
        <el-form-item label="启用状态" prop="status">
          <el-switch
            v-model="dataForm.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-value="启用"
            inactive-value="禁用">
          </el-switch>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button :size="size"  @click="dialogVisible = false">取消</el-button>
        <el-button :size="size"  type="primary" :loading="editLoading" @click="submitForm()">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import PermButton from '../../Component/PermButton/Index'
import { baseUrl } from '../../../utils/global'
export default {
    name: 'Adpic',
    components: {
        PermButton
    },
    data() {
        return {
            size: 'small',
            loading: false,
            editLoading: false,
            datas: [],
            upload: {
                url: baseUrl + '/common/image/upload',
                credentials: true,
                message: '',
                files: []
            },
            adTypeList: ['Banner图', '轮播图'],
            statusList: ['启用', '禁用'],
            dialogVisible: false,
            dataForm: {
                adId: 0,
                adType: '轮播图',
                originName: '',
                picUrl: '',
                url: '',
                status: '启用'
            },
            dataRule: {
                originName: [{ required: true, message: '图片名称不能为空', trigger: 'blur' }],
                picUrl: [{ required: true, message: '图片地址不能为空', trigger: 'blur' }],
                url: [{ required: true, message: '广告地址不能为空', trigger: 'blur' }]
            }
        }
    },
    methods: {
    // 获取数据
        findData: function() {
            this.loading = true
            this.$api.adpic.getAdpicList().then(res => {
                if (res && !res.success) {
                    this.$message({ message: res.message, type: 'error' })
                    this.loading = false
                    return
                }
                this.datas = res.data
                this.loading = false
            })
        },
        // 显示新增界面
        handleAdd: function() {
            this.dialogVisible = true
            this.dataForm = {
                adId: 0,
                adType: '轮播图',
                originName: '',
                picUrl: '',
                url: '',
                status: '启用'
            }
        },
        // 显示编辑界面
        handleEdit: function(row) {
            this.dialogVisible = true
            Object.assign(this.dataForm, row)
            this.upload.files = []
            this.upload.files.push({ name: this.dataForm.originName, url: this.dataForm.picUrl })
        },
        // 删除
        handleDelete(row) {
            this.$confirm('确认删除选中记录吗？', '提示', {
                type: 'warning'
            }).then(() => {
                const params = this.getDeleteIds([], row)
                this.$api.adpic.deleteAdpic(params).then(res => {
                    if (!res.success) {
                        this.$message({ message: res.message, type: 'error' })
                        return
                    }
                    this.findData()
                    this.$message({ message: '删除成功', type: 'success' })
                })
            })
        },
        // 获取删除的包含子分类的id列表
        getDeleteIds(ids, row) {
            ids.push(row.adId)
            if (row.children != null) {
                for (let i = 0, len = row.children.length; i < len; i++) {
                    this.getDeleteIds(ids, row.children[i])
                }
            }
            return ids
        },
        // 表单提交
        submitForm() {
            var callback = (res) => {
                this.editLoading = false
                if (res.success) {
                    this.$message({ message: '操作成功', type: 'success' })
                    this.$refs['dataForm'].resetFields()
                    this.dialogVisible = false
                } else {
                    this.$message({ message: res.message, type: 'error' })
                }
                this.findData()
            }
            this.$refs['dataForm'].validate(valid => {
                if (valid) {
                    this.$confirm('确认提交吗？', '提示', {}).then(() => {
                        this.editLoading = true
                        const params = Object.assign({}, this.dataForm)
                        // 处理枚举类型, ordinal
                        params.adType = this.adTypeList.findIndex(item => item === params.adType)
                        params.status = this.statusList.findIndex(item => item === params.status)
                        if (!this.dataForm.adId) {
                            this.$api.adpic.saveAdpic(params).then(res => {
                                callback(res)
                            })
                        } else {
                            this.$api.adpic.updateAdpic(params).then(res => {
                                callback(res)
                            })
                        }
                    })
                }
            })
        },
        handleBeforeUpload(file) {
            const isImage = file.type === 'image/jpeg' || 'image/gif' || 'image/png'
            const isLt1M = file.size / 1024 / 1024 < 1
            if (!isImage) {
                this.upload.message = '上传文件只能是图片格式!'
                this.$message({ message: this.upload.message, type: 'error' })
            }
            if (!isLt1M) {
                this.upload.message = '上传文件大小不能超过 1MB!'
                this.$message({ message: this.upload.message, type: 'error' })
            }
            return isImage && isLt1M
        },
        handleRemove(file, fileList) {
            this.upload.message = ''
            this.dataForm.picUrl = ''
            this.dataForm.originName = ''
        },
        handleError(err, file, fileList) {
            console.log(err)
            this.upload.message = '文件上传错误，请稍后再试'
            this.dataForm.picUrl = ''
            this.dataForm.originName = ''
            this.$message({ message: this.upload.message, type: 'error' })
        },
        handleSuccess(response, file, fileList) {
            console.log(file)
            if (response.success) {
                this.upload.message = ''
                this.dataForm.picUrl = response.data
                this.dataForm.originName = file.name
                this.$message({ message: '上传成功', type: 'success' })
            } else {
                this.upload.message = response.message
                this.dataForm.picUrl = ''
                this.$message({ message: response.message, type: 'error' })
            }
        },
        handleExceed(file, fileList) {
            if (fileList && fileList.length === 1) {
                this.upload.message = '文件上传超出限制，只能上传1个文件，请先删除再上传'
                this.$message({ message: this.upload.message, type: 'error' })
            }
        }
    },
    mounted() {
        this.findData()
    }
}
</script>

<style scoped>
</style>
